package com.saikei.demoapp

import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.saikei.demoapp.base.BaseInitVM
import com.saikei.demoapp.db.Book
import com.saikei.demoapp.db.DbDataBase
import com.saikei.demoapp.db.User

class MainVm(val app: Application) : BaseInitVM(app) {

    private val myDb: DbDataBase by lazy {
        DbDataBase.getInstance(app)
    }

    val mResult = MutableLiveData<String>()
    val mInput = MutableLiveData<String>()

    private var mUserId: Int? = null

    fun insertUser() {
        asyncLoad {
            myDb.userDao().insert(buildUser())
        }.onSuccess {
            Log.e("TAG", "日志: ${it.toString()}")
        }.onError {
            mResult.value = it.toString()
        }.onFinally {
            findAllUser()
        }
    }

    private fun buildUser(): User {
        return User(
            name = "${System.currentTimeMillis()}", password = "${System.currentTimeMillis()}"
        )
    }

    fun upsert(userId: Int) {
        asyncLoad {
            myDb.userDao().upsert(buildUser().apply {
                this.userId = userId
            })
        }.onSuccess {
            Log.e("TAG", "日志: ${it.toString()}")
            mResult.value = if (it == -1L) "成功${it}" else "失败${it}"
        }.onError {
            mResult.value = it.toString()
        }.onFinally {
            findAllUser()
        }
    }

    fun deleteUserWithBook(userId: Int) {
        asyncLoad {
            myDb.userDao().delete(userId)
        }.onError {
            mResult.value = it.toString()
        }.onFinally {
            findAllBook()
        }
    }

    fun insertUserBook(userId: Int?) {
        asyncLoad {
            myDb.bookDao().insert(Book(ownerUserId = userId, name = "nihao", password = "sssssss"))
        }.onError {
            mResult.value = it.toString()
        }.onFinally {
            findAllBook()
        }
    }

    fun findAllUser() {
        asyncLoad {
            myDb.userDao().findAll()
        }.onSuccess {
            Log.e("TAG", "日志: ${it.toString()}")
            var content = ""
            it.toList().onEach {
                content += "\n${it.toString()}"
            }
            mResult.value = content
        }.onError {
            mResult.value = it.toString()
            Log.e("TAG", "日志: ${it.toString()}")
        }
    }

    private fun findAllBook() {
        asyncLoad {
            myDb.bookDao().findAll()
        }.onSuccess {
            Log.e("TAG", "日志: ${it.toString()}")
            var content = ""
            it.toList().onEach { book ->
                content += "\n${book.toString()}"
            }
            mResult.value = content
        }.onError {
            mResult.value = it.toString()
            Log.e("TAG", "日志: ${it.toString()}")
        }
    }

    fun findUserBookList(userId: Int) {
        asyncLoad {
            myDb.userWithBookDao().findBookFormUserId(userId)
        }.onSuccess { it ->
            var content = if (it?.user == null) {
                ""
            } else {
                it.user.toString()
            }
            it?.books?.onEach { book ->
                content += "\n书籍：${book.toString()}"
            }.takeIf { !it.isNullOrEmpty() }.apply {
                content += "\n该用户暂没有书籍"
            }
            mResult.value = content.toString()
            Log.e("TAG", "日志1: ${it.toString()}")
        }.onError {
            mResult.value = it.toString()
            Log.e("TAG", "日志2: ${it.toString()}")
        }
    }

}